<template>
    <div>
        <el-button class="back-btn" type="primary" icon="el-icon-arrow-left" plain style="margin-right: 25px" @click="goBack">返回</el-button>
        <div class="pdf-warp" ref="pdf" v-loading="loadState">
            <pdf :src="src"
                 :page="currentPage"
                 @num-pages="pageCount=$event"
                 @page-loaded="currentPage=$event"
                 @loaded="loadPdfHandler"
                 @error="onError"
            >
            </pdf>
        </div>
        <el-pagination
                class="pager"
                @current-change="pageChange"
                :current-page.sync="currentPage"
                layout="total, jumper, ->, prev, pager, next"
                :total="pageCount"
                :page-size="1"
                :size="1"
                :pager-count="7"
                background>
        </el-pagination>
    </div>
</template>

<script>
    import pdf from 'vue-pdf';

    export default {
        name: "PdfPreviewer",
        components:{pdf},
        props:{
            src:String
        },
        data(){
            return{
                currentPage: 1, // pdf文件页码
                pageCount: 0, // pdf文件总页数
                loadState: true
            }
        },
        methods:{
            // pdf加载时
            loadPdfHandler (e) {
                this.currentPage = 1 // 加载的时候先加载第一页
                this.$refs.pdf.scrollTop = 0;
                this.loadState = false;
            },pageChange(index){
                this.scrollToTop();
            },goBack(){
                this.$emit("exit");
            },scrollToTop(){
                const timer = setInterval(()=>{
                    if(this.$refs.pdf.scrollTop<=160){
                        this.$refs.pdf.scrollTop = 0;
                        clearInterval(timer);
                    }
                    this.$refs.pdf.scrollTop -= 160;
                },20)
            },onError(e){
                console.log(e);
                this.$alert("pdf文件加载失败。",'无法预览',{type:'error'});
            }
        }
    }
</script>

<style scoped>
    .pdf-warp{
        overflow: auto;
        position: absolute;
        top: 3px;
        left: 3px;
        right: 12px;
        bottom: 5px;
        z-index: 5;
        background-color: white;
    }
    .back-btn{
        position: absolute;
        top: 25px;
        right: 35px;
        z-index: 100;
    }
    .pager{
        position: absolute;
        bottom: 8px;
        left: 12px;
        right: 24px;
        z-index: 12;
    }
</style>
